import { ReactiveProperty } from './../libs/rxjs/cc3/ReactiveProperty';
import { BaseManager } from './../libs/rxjs/cc3/BaseManager';
import { _decorator, color, director, System, sys } from 'cc';
import { i18n } from '../i18n';
const { ccclass, property } = _decorator;

@ccclass('UserDataManager')
export class UserDataManager extends BaseManager {

    public static instance: UserDataManager;
    static ID = 'userdata_system';
    get logColorOverride() { return color().fromHEX('#EEDDDD') };

    localstorageKey = 'profile_0';

    static registerSystem() {
        director.unregisterSystem(director.getSystem(UserDataManager.ID));
        director.registerSystem(UserDataManager.ID, udm, System.Priority.MEDIUM);
        udm.init();
    }

    onInitManager() {
        this.log('onInitManager', this.timestamp);
        this.load();
    }

    bgmOn = ReactiveProperty.Create(true);
    sfxOn = ReactiveProperty.Create(true);
    vibrateOn = ReactiveProperty.Create(true);
    lang = ReactiveProperty.Create('en');

    useObserves() {
        return [
            this.lang.subscribe(_ => {
                i18n.init(this.lang.value);
                i18n.updateSceneRenderers();
            })
        ];
    }

    stringify() {
        return JSON.stringify({
            bgm: this.bgmOn.value,
            sfx: this.sfxOn.value,
            vibrate: this.vibrateOn.value,
            lang: this.lang.value,
        });
    }

    correct() {
    }

    parse(str) {
        let obj = {} as any;
        if (str != null && str != '') {
            obj = JSON.parse(str);
        }
        this.bgmOn.value = obj?.bgm ?? true;
        this.sfxOn.value = obj?.sfx ?? true;
        this.vibrateOn.value = obj?.vibrate ?? true;
        this.lang.value = obj?.lang ?? 'en';
    };

    clear() {
        sys.localStorage.removeItem(this.localstorageKey);
    }

    save() {
        this.correct();
        let str = this.stringify();
        sys.localStorage.setItem(this.localstorageKey, str);
        this.parse(str);
    }

    load() {
        let str = sys.localStorage.getItem(this.localstorageKey);
        this.parse(str);
        this.initialize();
    }

    initialize() {
    }

}

globalThis.UserDataManager = UserDataManager;

export const udm = UserDataManager.instance = new UserDataManager();